#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
require Exporter;
use strict;
use SIM_settings;
use SIM_base;
use CGI qw(param);
use Sys::Hostname;

my $httpUser = $ENV{'REMOTE_USER'} || die "Oops no env found for REMOTE_USER.";
my $serverIp = $ENV{'HTTP_HOST'} || die "Oops no env found for HTTP_HOST.";
my $groupDir = $ENV{'SIM_passwdGroupDir'} || die "Oops no env found for SIM_passwdGroupDir.";
my $userDir = $ENV{'SIM_passwdUserDir'} || die "Oops no env found for .";
my $simBaseDir = $ENV{'SIM_BASEDIR'} || die "Oops no env found for SIM_BASEDIR.";
my $settingsDir = $ENV{'SIM_SETTINGSD'} || die "No env SIM_SETTINGSD found.";
my $htaccessFile = $ENV{'SIM_HTTPPWDLIST'} || die "No env SIM_HTTPPWDLIST found.";
my $tmpDir = $ENV{'SIM_TMPDIR'} || die "No env SIM_TMPDIR found.";
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];
my $option4 = $ARGV[6];


sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
    }
    print OUT $rest;
    close(OUT);
  }
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    if ( "$update" eq "upd" ) { 
      printFileLine("$file","$parameter","$result","nquiet");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub printHead {
  my $dispHead = "@_[0]";
  print("
        <TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD COLSPAN=3><CENTER>
        Options:
        <A HREF=$httpScriptName?$module+$tool+list>List</A> <FONT COLOR=#333333>|</FONT>
	Add:
        <A HREF=$httpScriptName?$module+$tool+updGroup>Group</A> <FONT COLOR=#333333>|</FONT>
        <A HREF=$httpScriptName?$module+$tool+updUser>User</A>
	</TD></TR>
	</TABLE>
        ");
}

sub readUpdParam {
  my $workFile = "@_[0]";
  my $name = "@_[1]";
  my $type = "@_[2]";
  my $param = param("$name");
  if ( "$type" eq "fill" ) {
    $param=~s/ /_/g;
  }
  if ( "$param" eq "" ) {
    $param = catFileLine("$workFile");
  } else {
    printFileLine("$workFile","$name","$param");
  }
  return $param;
}

sub modUser {
  my $userName = "@_[0]";
  if ( -d "$userDir/$userName" ) {
    my $realName = readUpdParam("$userDir/$userName/userName","realName");
    my $email = readUpdParam("$userDir/$userName/emailAddr","email");
    my $group = readUpdParam("$userDir/$userName/group","group");
    print("<CENTER>
      <H2>Updating info for $userName.</H2>
      <TABLE>
      <FORM method=post Action=$httpScriptName?$module+$tool+modUser+$userName>
        <TR><TD>Domain:</TD><TD>
          <SELECT NAME=group SIZE=1>
            <OPTION VALUE=$group>$group</OPTION>
          ");
    chdir "$groupDir";
    my @groupList = <*>;
    foreach my $entry (@groupList) {
      print("<OPTION VALUE=$entry>group: $entry</OPTION>");
    }
    print("</SELECT>
      <TR><TD>Username:</TD><TD><INPUT NAME=realName Size=50 Type=text VALUE=\"$realName\"></TD></TR>
      <TR><TD>EmailAdr:</TD><TD><INPUT NAME=email Size=50 Type=text VALUE=\"$email\"></TD></TR>
      <TR><TD COLSPAN=2><CENTER><INPUT TYPE=submit Value=\"Update user\"></TD></TR>
      <TR><TD COLSPAN=2><B>Other actions</B></TD></TR>
      <TR><TD>Password:</TD><TD><A HREF=$httpScriptName?$module+$tool+restPwd+$userName>reset</A></TD></TR>
      <TR><TD>Delete user:</TD><TD><A HREF=$httpScriptName?$module+$tool+delUser+$userName>remove</A></TD></TR>
    </TABLE>
    </FORM>
          ");
  }
}

sub delUser {
  my $userName = "@_[0]";
  if ( -d "$userDir/$userName" ) {
    print("Removing password for $userName. ");
    system(" htpasswd -D $htaccessFile $userName ");
    print("<BR>Removing data for $userName. ");
    system(" rm -fr $userDir/$userName ");
    if ( ! -d "$userDir/$userName" ) {
      print("User $userName removed successfully.<HR>");
    } else {
      print("Oops, problems removing the data for user $userName.<BR>");
    }
    &listAll;
  } else {
    print("Oops, no data found for user $userName.<BR>");
  }
}

sub updUser {
  my $userName = "@_[0]";
  if (( "$userName" eq "none" ) or ( "$userName" eq "" )){
    $userName = param("userName");
  }
  my $groupName = param("groupName");
  print("<CENTER><TABLE><TR><TD>");
  if ( "$userName" eq "" ) {
    print("
      <FORM method=post Action=$httpScriptName?$module+$tool+updUser>
        UserID: <INPUT NAME=userName Size=12 Type=text>
        <INPUT TYPE=submit Value=\"Add user\">
      </FORM>
          ");
  } elsif ( "$groupName" ne "" ) {
    print("Updating group to $groupName for $userName: ");
    mkdir "$userDir/$userName";
    printFileLine("$userDir/$userName/group","groupname",$groupName);
    print("<HR>");
    &modUser($userName);
  } else {
    print("</H2>Updating user: \"$userName\"</H2>
    <FORM method=post Action=$httpScriptName?$module+$tool+updUser+$userName>
        Add / modify domain: <SELECT NAME=groupName SIZE=1>
          <OPTION VALUE=>Please select.</OPTION>
          ");
    chdir "$groupDir";
    my @groupList = <*>;
    foreach my $entry (@groupList) {
      print("<OPTION VALUE=$entry>group: $entry</OPTION>");
    }
    print("</SELECT>
        <INPUT TYPE=submit Value=\"Set group\">
      </FORM>
          ");
  }
  print("</TD></TR></TABLE>");
}

sub updGroup {
  my $groupName = "@_[0]";
  my $domainName = param("domainName");
# print("groupName=$groupName. ");
  if (( "$groupName" eq "" ) or ( "$groupName" eq "none" )){
    $groupName = param("groupName");
  }
  print("<CENTER><TABLE><TR><TD>");
  if ( "$groupName" eq "" ) {
    print("
      <FORM method=post Action=$httpScriptName?$module+$tool+updGroup>
        Groupname: <INPUT NAME=groupName Size=12 Type=text>
        <INPUT TYPE=submit Value=\"Add group\">
      </FORM>
          "); 
  } elsif ( "$domainName" ne "" ) {
    print("Updating domain $domainName for group $groupName: ");
    my $accessLevel = param("accessLevel");
    if ( ! -d "$groupDir/$groupName" ) { system(" mkdir $groupDir/$groupName"); }
    printFileLine("$groupDir/$groupName/accessLevel-$domainName","accessLevel-$groupName",$accessLevel);
    print("<HR>");
    &listAll;
  } else {
    print("<H2>Updating group: \"$groupName\"</H2>
    <FORM method=post Action=$httpScriptName?$module+$tool+updGroup+$groupName>
        Add / modify domain: <SELECT NAME=domainName SIZE=1>
          <OPTION VALUE=>Please select.</OPTION>
          <OPTION VALUE=all>All domains</OPTION>
          ");
    chdir "$simBaseDir/data";
    my @domainList = <*>;
    foreach my $entry (@domainList) {
      print("<OPTION VALUE=$entry>domain: $entry</OPTION>");
    }
    print("</SELECT>
        <SELECT NAME=accessLevel>
          ");
    foreach my $num ( 1 .. 9 ) {
      print("<OPTION VALUE=$num>access-level: $num</OPTION>");
    }
    print("</SELECT>
        <INPUT TYPE=submit Value=\"Set access-level\">
        </FORM>
          ");
    my $defaultAction = testUpdFile("$groupDir/$groupName/defaultAction", "defaultAction", "default action");
    my $devicesMonitored = testUpdFile("$groupDir/$groupName/devicesMonitored", "devicesMonitored", "devices monitored");
    my $devicesVisible = testUpdFile("$groupDir/$groupName/devicesVisible", "devicesVisible", "devices visible");
    my $errorLogging = testUpdFile("$groupDir/$groupName/errorLogging", "errorLogging", "error logging");
    my $otherLogging = testUpdFile("$groupDir/$groupName/otherLogging", "otherLogging", "other logging");
    print("<FORM method=post Action=$httpScriptName?$module+$tool+updGroup+$groupName>
        <TABLE>
        <TR><TD>Default action:</TD><TD><INPUT NAME=defaultAction Size=50 Type=text VALUE=\"$defaultAction\"></TD>
             <TD>Use the first two parts of the menu action you want. eg. \"mon subnets\"</TD></TR>
        <TR><TD>Devices monitored:</TD><TD><INPUT NAME=devicesMonitored Size=50 Type=text VALUE=\"$devicesMonitored\"></TD>
             <TD>define the device vendors that need to be monitored by this group, or all (separate by spaces in case of multiple groups</TD></TR>
        <TR><TD>Devices visible:</TD><TD><INPUT NAME=devicesVisible Size=50 Type=text VALUE=\"$devicesVisible\"></TD>
             <TD>define the devices in the device menu that will be visible for this group</TD></TR>
        <TR><TD>Error logging:</TD><TD><INPUT NAME=errorLogging Size=50 Type=text VALUE=\"$errorLogging\"></TD>
             <TD>default logging shown in the monitor window.</TD></TR>
        <TR><TD>Other logging:</TD><TD><INPUT NAME=otherLogging Size=50 Type=text VALUE=\"$otherLogging\"></TD>
             <TD>other logging groups accessible for this group.</TD></TR>
        </TABLE>
        <CENTER><INPUT TYPE=submit Value=\"Set parameters\">
      </FORM>
          ");
  }
  print("</TD></TR></TABLE>");

}

sub defaultAction {
  my $groupName = "@_[0]";
  my $defaultAction = param("defaultAction");
  print("$groupDir/$groupName/defaultAction ");
  printFileLine("$groupDir/$groupName/defaultAction","Default action for $groupName", $defaultAction);
  &listAll;
}

sub restPwd {
  my $userName = "@_[0]";
  my $random = int(rand(1000000));
  if ( "$random" < "100000" ) {
    $random = $random + 100000;
  }
  my $newPwd = "Pwd$random";
  system(" htpasswd -b $htaccessFile $userName $newPwd ");
  if ( -f "$settingsDir/pwdUpdTime-$userName" ) {
    unlink("$settingsDir/pwdUpdTime-$userName");
  }
  print("Temporary password for $userName has been set to \"$newPwd\". ");
  my $mailFile = "$tmpDir/pwdChange-$userName";
  my $realName = catFileLine("$userDir/$userName/userName");
  my $emailAddr = catFileLine("$userDir/$userName/emailAddr");
  my $host = hostname();
  if ( "$emailAddr" ne "" ) {
    open(MAIL , ">$mailFile") || die "Oops could not create your mailfile.";;
    print MAIL ("Hi $realName,
Your password for userid $userName at system $host has been reset to $newPwd.

If you login to the system ($serverIp/sipman3/) you will have to change your password.

Hope you enjoy the system,

Sincerely,

The sipman process.

P.s.
Please use Firefox for this action. Unfortunately a bug was found in
Explorer, which seems to cache the password inspite of requesting the new one.");
    close MAIL;
    system(" mailx -s \"Password reset for your Sipman userid\" $emailAddr < $mailFile ");
    unlink $mailFile;
    printf("Mail sent to $emailAddr.");
  }
  
}

sub listAll {
  my %domainUsers = ();
  my %userLine = ();
  chdir $userDir;
  my @userList = <*>;
  foreach my $entry (@userList) {
    my $domain = catFileLine("$userDir/$entry/group");
    my $userName = catFileLine("$userDir/$entry/userName");
    my $emailAddr = catFileLine("$userDir/$entry/emailAddr");
    $domainUsers{$domain} = "$domainUsers{$domain} $entry";
    my $lastIp = catFileLine("$userDir/$entry/lastIP");
    my $lastActive = my $time = (stat "$userDir/$entry/lastIP")[9];
    my $dateString = printDate($time,"yyyymmdd");
    $userLine{$entry} = "<TR><TD></TD><TD BGCOLOR=#DD88DD>User</TD>
                                      <TD BGCOLOR=#DDAADD><A HREF=$httpScriptName?$module+$tool+modUser+$entry>$entry</A></TD>
                                      <TD BGCOLOR=#DDAADD>$userName</TD>
                                      <TD BGCOLOR=#DDAADD>$dateString / $lastIp</TD>
                                      <TD BGCOLOR=#DDAADD><A HREF=mailto:$emailAddr>$emailAddr</A></TD></TR>";
  }
  print("<CENTER><TABLE>");
  chdir $groupDir;
  my @groupList = <*>;
  foreach my $entry (@groupList) {
    print("<TR BGCOLOR=#AADDDD><TD><A HREF=$httpScriptName?$module+$tool+updGroup+$entry>$entry</A></TD><TD>Groupname</TD></TR>");
    chdir "$groupDir/$entry";
    my @accessLevels = <accessLevel-*>;
    foreach my $aclEntry (@accessLevels) {
      my $aclDomain = substr( $aclEntry, 12 );
      my $accessLevel = catFileLine("$aclEntry");
      print("<TR>
               <TD></TD>
               <TD BGCOLOR=#88BBBB>Access level domain</TD>
               <TD COLSPAN=4 BGCOLOR=#AABBBB>$aclDomain = $accessLevel</TD>
            </TR>");
    }
    my $defaultAction = catFileLine("$groupDir/$entry/defaultAction");
    print("<TR><TD></TD><TD BGCOLOR=#CCEEEE>Default action</TD><TD COLSPAN=4 BGCOLOR=#CCEEEE>$defaultAction</TD></TR>");
    my $devicesMonitored = catFileLine("$groupDir/$entry/devicesMonitored");
    print("<TR><TD></TD><TD BGCOLOR=#CCEEEE>Devices monitored</TD><TD COLSPAN=4 BGCOLOR=#CCEEEE>$devicesMonitored</TD></TR>");
    my $devicesVisible = catFileLine("$groupDir/$entry/devicesVisible");
    print("<TR><TD></TD><TD BGCOLOR=#CCEEEE>Devices visible</TD><TD COLSPAN=4 BGCOLOR=#CCEEEE>$devicesVisible</TD></TR>");
    my $errorLogging = catFileLine("$groupDir/$entry/errorLogging");
    print("<TR><TD></TD><TD BGCOLOR=#CCEEEE>Error logging</TD><TD COLSPAN=4 BGCOLOR=#CCEEEE>$errorLogging</TD></TR>");
    my $otherLogging = catFileLine("$groupDir/$entry/otherLogging");
    print("<TR><TD></TD><TD BGCOLOR=#CCEEEE>Other logging</TD><TD COLSPAN=4 BGCOLOR=#CCEEEE>$otherLogging</TD></TR>");
    
    my @userList = split(' ', $domainUsers{$entry});
    foreach my $userName (@userList) {
      if ( $userLine{$userName} ne "" ) {
        print("$userLine{$userName}\n");
      }
    }
  }
  print("</TABLE>");
}

#--------------------------- Main ---------------------------
printHead;



if ( ! -d $groupDir ) {
  print("Oops, no group directory present........");
} elsif ( ! -d $userDir ) {
  print("Oops, no user directory present........");
} elsif ( "$action" eq "updGroup" ) {
  updGroup( $option1, $option2, $option3, $option4);
  #updGroup( $option1, $option2, $option3, $option4);
} elsif ( "$action" eq "updUser" ) {
  updUser( $option1, $option2, $option3);
} elsif ( "$action" eq "modUser" ) {
  modUser( $option1, $option2, $option3);
} elsif ( "$action" eq "restPwd" ) {
  restPwd( $option1, $option2, $option3);
} elsif ( "$action" eq "delUser" ) {
  delUser( $option1, $option2, $option3);
} elsif ( "$action" eq "defaultAction" ) {
  defaultAction( $option1, $option2, $option3);
} else {
  listAll( $option1, $option2, $option3);
}
